<template>
	<x-popup v-model="show" height="60vh" @hide="close">
		<view class="flex flex-center grid-gap-4">
			<view class="flex-1 text-center p-4 h9 font-weight-600">选择使用优惠券</view>
		</view>
		<view class="bg flex-1 p-4 grid-gap-4 overflow-y-auto flex flex-column" v-if="couponList.length > 0">
			<x-coupon-item v-for="(item, index) in couponList" :key="index" :item="item">
				<template #action>
					<button class="btn-primary btn-round" size="mini" v-if="hasUse(item)" @click="use(item)">使用</button>
					<button class="btn-placeholder btn-round shadow text-nowrap" size="mini" v-else>暂不可用</button>
				</template>
			</x-coupon-item>
		</view>
		<view class="flex-1 flex flex-center" v-else>
			<x-empty type="order" text="无可用优惠券"></x-empty>
		</view>
		<view class="pb-safe-area"></view>
	</x-popup>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, onMounted } from 'vue';
import { $api } from '@/utils';
const props = withDefaults(defineProps<{
	show: boolean
	price: Number
	list?: any
}>(), {
	show: false,
	price: 0,
	list: []
});
const emit = defineEmits(['confirm', 'update:show'])
const selected = ref([]);
const show = ref(props.show);
const couponList = ref([]);
watch(() => props.price, (val: number) => {
	for (let i = 0; i < selected.value.length; i++) {
		const item = selected.value[i];
		switch (item.use_type) {
			case 'FULL_DEC':
				if (val < item.full_money) {
					selected.value.splice(i, 1);
					close();
				}
				break;
		}
	}
})
const getCoupon = () => {
	$api.Coupon.getAvailable().then((res: any) => {
		couponList.value = res.data;
	}).catch(() => { })
}
const hasUse = (item: any) => {
	switch (item.use_type) {
		case 'FULL_DEC':
			return props.price >= item.full_money;
		case 'DEC':
			return true;
		default:
			return false;
	}
}
const use = (item: any) => {
	selected.value = [item];
	emit('confirm', {
		ids: [item.code],
		coupon: [item]
	})
	show.value = false;
}
const close = (e?: any) => {
	if (e && e.type === 'mask') {
		emit('confirm')
	}
}
watch(()=>show.value,(val:boolean) => {
	emit('update:show',val);
})
watch(() => props.show, (val: boolean) => {
	show.value = val;
	if (val) {
		getCoupon();
	}
})
onMounted(() => {
	couponList.value = props.list;
	if (props.show) {
		getCoupon();
	}
})
</script>
